<template>
  <div>
    <el-row :gutter="20" v-if="!finish">
      <el-col :span="8" :offset="8">
        <el-card class="box-card">
          <div slot="header" style="display: flex">
            <div class="back-icon" @click="backPage">
              <i class="el-icon-arrow-left"></i>
            </div>
            <span class="my-font header-title">{{ evaTitle }}</span>
          </div>
          <div v-if="currentQuestion" class="question-body">
            <div class="question-title">
              {{ currentQuestion.sort }}、{{ currentQuestion.title }}
            </div>
            <div v-if="currentQuestion.image" class="my-image">
              <el-image :src="currentQuestion.image" fit="fit"></el-image>
            </div>

            <!-- 在 el-radio-group 中使用 div 包装每个 el-radio -->
            <el-radio-group v-model="selectedValues">
              <div
                v-for="option in options"
                :key="option.optionid"
                class="question-option"
              >
                <el-radio :label="option.value" class="question-radio">
                  {{ option.value }}、{{ option.title }}
                </el-radio>
              </div>
            </el-radio-group>
          </div>

          <!-- 上一题和下一题按钮 -->
          <div class="my-btn">
            <div>
              <el-button
                @click="prevQuestion"
                :disabled="currentQuestionIndex === 0"
              >
                上一题
              </el-button>
              <el-button
                @click="nextQuestion"
                v-if="currentQuestionIndex < questionList.length - 1"
              >
                下一题
              </el-button>
              <el-button @click="submitEvaluation" v-else>提交</el-button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <EvaResult
      :evaluateId="evaluateId"
      :result="result"
      v-if="finish"
    ></EvaResult>
  </div>
</template>

<script>
import EvaResult from "./EvaResult.vue";
export default {
  components: { EvaResult },
  created() {
    this.evaluateId = this.$route.params.evaluateId;
    this.init();
  },
  data() {
    return {
      evaluateId: "", //测试id
      evaTitle: "", //测试主题
      questionList: [], //问题列表
      currentQuestionIndex: 0, //当前问题索引
      options: [], //问题选项
      selectedValues: [], // 记录选择的值
      answers: [], // 存储每个问题的选择值
      totalScore: 0, //总得分
      finish: false, //是否完成测试
      result: "", //测试结果
    };
  },
  computed: {
    //问题对象
    currentQuestion() {
      return this.questionList[this.currentQuestionIndex];
    },
    //当前问题的id
    questionId() {
      return this.currentQuestion.questionid;
    },
  },
  methods: {
    backPage() {
      this.$confirm("现在退出，您的测试将不会保存，是否退出?", "退出测试", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$router.back();
        })
        .catch(() => {});
    },
    init() {
      this.getEvaInfo();
      this.getEvaQuestions();
    },
    //获取测试信息
    getEvaInfo() {
      this.$request.getHttp({
        url: "/evaluate/getEvaluateById",
        params: { evaluateId: this.evaluateId },
        success: (data) => {
          if (data.code == 200) {
            this.evaTitle = data.evaluate.title;
          }
        },
        error: (error) => {},
      });
    },
    //获取测试题
    getEvaQuestions() {
      this.$request.getHttp({
        url: "/evaluatequestion/getQuestionsListByEvaluateId",
        params: {
          evaluateId: this.evaluateId,
        },
        success: (data) => {
          if (data.code == 200) {
            this.questionList = data.list;
            this.answers = new Array(this.questionList.length);
            console.log(this.questionList);
            if (this.questionList) {
              //获取第一个问题的选项
              this.getQuestionOptions(this.questionList[0].questionId);
            }
          }
        },
        error: (error) => {},
      });
    },
    //获取问题选项
    getQuestionOptions(questionId) {
      this.$request.getHttp({
        url: "/questionoption/getQuestionOptionByQuestionId",
        params: { questionId: questionId ? questionId : this.questionId },
        success: (data) => {
          if (data.code == 200) {
            this.options = data.list;
          }
        },
        error: (error) => {},
      });
    },

    // 上一题
    prevQuestion() {
      if (this.currentQuestionIndex > 0) {
        // 保存当前问题的选择
        this.answers[this.currentQuestionIndex] = this.selectedValues;
        // 切换到上一题
        this.currentQuestionIndex--;
        // 恢复上一题的选择（如果已经选择过）
        this.selectedValues = this.answers[this.currentQuestionIndex] || [];
        this.getQuestionOptions(
          this.questionList[this.currentQuestionIndex].questionId
        );
      }
    },

    // 下一题
    nextQuestion() {
      if (this.currentQuestionIndex < this.questionList.length - 1) {
        // 保存当前问题的选择
        this.answers[this.currentQuestionIndex] = this.selectedValues;
        // 切换到下一题
        this.currentQuestionIndex++;
        // 恢复下一题的选择（如果已经选择过）
        this.selectedValues = this.answers[this.currentQuestionIndex] || [];
        this.getQuestionOptions(
          this.questionList[this.currentQuestionIndex].questionId
        );
      }
    },

    // 提交测试逻辑
    submitEvaluation() {
      //获取最后一个值
      this.answers[this.currentQuestionIndex] = this.selectedValues;

      // 检查数组中是否包含 null 或 undefined
      const hasNullOrUndefined = this.answers.some(
        (value) => value === null || value === undefined || value.length == 0
      );
      if (hasNullOrUndefined) {
        this.$message({
          message: "请填写完所有的问题再提交！",
          type: "warning",
        });
        return;
      }

      // 提交
      this.calculateAndReturnResultByEvaluateId(this.answers);
    },
    calculateAndReturnResultByEvaluateId(options) {
      this.$request.postHttp({
        url: "/evaluatequestion/calculateAndReturnResultByEvaluateId",
        data: {
          evaluateId: this.evaluateId,
          options: options,
        },
        success: (data) => {
          if (data.code == 200) {
            this.result = data.result;
            this.finish = true;
            this.addEvaluateRecord();
          }
        },
        error: (error) => {},
      });
    },
    //添加一条记录
    addEvaluateRecord() {
      this.$request.postHttp({
        url: "/evaluaterecord/addEvaluateRecord",
        data: {
          evaluateid: this.evaluateId,
          userid: localStorage.getItem("userId"),
          date: new Date(),
          result: this.result,
        },
        success: (data) => {
          console.log(data);
        },
        error: (error) => {},
      });
    },
  },
};
</script>

<style scoped>
.back-icon {
  width: 2vw;
  font-size: 20px;
  cursor: pointer;
}

.header-title {
  width: 27vw;
  display: flex;
  justify-content: center;
  align-items: center;
}

.my-font {
  font-weight: bold;
  font-size: 20px;
}

.question-body {
  width: 30vw;
}

.question-title {
  margin-left: 2vw;
}

.my-image {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 2vw;
}

.question-option {
  margin-left: 3.5vw;
  margin-top: 1vh;
}

.my-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 1vh;
}
</style>